
const alertOnlineStatus = () => {
	//window.alert(navigator.onLine ? 'online' : 'offline')
	// 监听网络的连接状态, 联网不代表能访问到服务端
	let msg = navigator.onLine ? 'online' : 'offline'
	ipcRenderer.send('app-onlinemessage', msg)
}
let __wsPushContentTime = null;
/**
 * 加载轮播内容页面
 * @param {*} loadPage 
 */
function pushLoadContentPage(loadPage) {
	if(loadPage["contentlist"]){
		for (var i=0;i< loadPage["contentlist"].length;i++) {
			loadPage["contentlist"][i]["url"] = VisualConst.appendDeviceParam(loadPage["contentlist"][i]["url"]);
		}
	}
	flag = false;
	if(null===__wsPushContentTime){
		__wsPushContentTime = new Date().getTime();
		flag = true;
	}else{
		let c = ((new Date().getTime()) - __wsPushContentTime);
		__wsPushContentTime = new Date().getTime();
		if(c<1500){
			flag = false;
		}else{
			flag = true;
		}
	}
	flag = true;
	//首页中显示推送的所有看板列表（允许用户给每个看板，指定显示到哪个显示器）
	if(true===flag){
		let dataVDisplay = VisualConst.getDataVDisplay();
		
		var template = require('art-template');
		let contentlist = loadPage["contentlist"];
		contentlist.forEach(it => {
			it.displayId = dataVDisplay[""+it.id] || "";
		});
		var html = template.render($("#datav_item_html").html(), {
			datavlist:contentlist,
			displayItems:__allDisplays||[]
		});
		//初始之前，获取到上一次的配置，初始化默认选中值
		$("#datavlist").html(html);
		$("#btnSaveDatavDisplay").off("click");
		$("#btnSaveDatavDisplay").on("click",function(event) {
			// 遍历每一组输入框
			let displayCfg ={};
			$('.visual_item').each(function() {
				var datavid = $(this).find('input[name="datavid"]').val(); 
				var datavdisplay = $(this).find('select[name="datavdisplay"]').val();   
				// 将数据存储为对象
				if (datavdisplay && datavid) { // 如果 name 或 age 有值，才添加到数据中
					displayCfg[""+datavid] = datavdisplay;
				}
			});
			// console.log("多屏配置",displayCfg,$("#display-form").serializeArray());
			VisualConst.setDataVDisplay(displayCfg);
			Qmsg.success("保存成功，重新加载！");
			loadMainPage();
		});

		$("#btnHideDatavDisplay").off("click");
		$("#btnHideDatavDisplay").on("click",function(event) {
			$("#display-form").hide();
		});
		
		//创建多屏看板内容
		ipcRenderer.send('app-loadContentPage', loadPage);
	}
}

/**
 * 收到服务端推送的事件回调
 * @param {*} e 
 */
function clientIndexEvent(e) {
 	if (e["data"]["eventkey"] == "SCREENSHOT") {
		clientDesktopCapturer({}, function(picdata) {
			//图片的base64 地址
			//console.log(picdata)
			VisualReq.eventCallback(e, picdata, function(re) {
				//console.log(re);
			});
		})
	} else if (e["data"]["eventkey"] == "RESTARTAPP") {
		ipcRenderer.send('app-clientEvent', e);
	} else if (e["data"]["eventkey"] == "RELOADSCREEN") {
		//重新加载大屏内容
		reConnectOpen();
	}
}
/**
 * 收到服务端推送的消息 回调
 * @param {*} data 
 */
function clientIndexHandleMessage(data) {
	switch (data.pushtype) {
		case 'screens':
			//展示内容
			VisualConst.setLastContent(data);
			pushLoadContentPage(data);
			break;
		case 'event':
			//用来扩展 比如 要求客户端截图 ，获取客户端内存信息,主动触发更新 等场景
			clientIndexEvent(data);
			break;
		case 'exitreconn':
			___lastConnServerStatus = "noauth";
			setStatusText("验证失败，请联系管理员");
			break;
		case 'regack':
			
			updateServerInfo(data);
			break;
	}
}

/**
 * 连接服务器
 */
function connectWsServer() {
	var wsParams = VisualConst.getAppCfg()['ws'];
	var serverInfo = VisualConst.getServerInfo();

	wsParams["ws_ip"] = serverInfo["ip"] || wsParams["ws_ip"];
	wsParams["ws_port"] = serverInfo["port"] || wsParams["ws_port"];
	wsParams["token"] = serverInfo["token"] || "";
	wsParams['deviceip'] = ____clientStaticData["network"]["address"] || "none";
	wsParams['deviceid'] = VisualConst.getCustomDevice({})["deviceid"];
	wsParams['reconnInterval'] = 10000;
	wsParams["appid"] = VisualConst.getAppCfg()['comm']['appid'];
	wsParams['serverType'] = serverInfo["serverType"] || '1';
	wsParams['remark'] = serverInfo["remark"] || '';
	
	if(wsParams['serverType']=='2'){
		wsParams["ws_port"] = "";//连接云平台时，不配置端口，端口配置到链接地址中
	}
	if(wsParams["ws_ip"].indexOf("wss://")==0){
		wsParams["ws_ip"] = wsParams["ws_ip"].substring(wsParams["ws_ip"].indexOf("wss://")+6);
		wsParams["ws_protocol"] = "wss";//
	}else if(wsParams["ws_ip"].indexOf("ws://")==0){
		wsParams["ws_ip"] = wsParams["ws_ip"].substring(wsParams["ws_ip"].indexOf("ws://")+5);
		wsParams["ws_protocol"] = "ws";//
	}else{
		
	}
	initScreenWs(wsParams); //链接服务
}
function setStatusText(status) {
	$("#client_status").html(status);
}
function updateServerInfo(data){
	var info = (data.data || {});
	
	____clientDeviceInfo["locationId"] = info["locationId"];
	____clientDeviceInfo["locationName"] = info["locationName"];
	____clientDeviceInfo["remark"] = info["locationRemark"];
	____clientDeviceInfo["deviceName"] = info["deviceName"];
	
	var serverInfo = VisualConst.getServerInfo();
	serverInfo["locationId"] = info["locationId"];
	serverInfo["locationName"] = info["locationName"];
	serverInfo["remark"] = info["locationRemark"];
	serverInfo["deviceName"] = info["deviceName"];
	VisualConst.setServerInfo(serverInfo);
	
}
/**
 * 服务器连接状态回调
 * @param {*} event 
 * @param {*} e 
 * @param {*} ws 
 */
function clientIndexHandleWsConn(event, e, ws) {
	//"onclose" onopen
	if (event == "onclose") {

		console.log("连接关闭断开=",new Date(),event,e,ws);
		//1，关闭展示内容
		if(ws.reconnStatus!=0){
			//2，设置状态显示
			setStatusText("已断开连接");
		}else{
			//2，设置状态显示
			setStatusText("验证失败，请联系管理员");
		}
	} else if (event == "onopen") {
		var msg = {
			errcode: '100000',
			errmsg: 'open websocket'
		};
		ipcRenderer.send('app-socket-onlinemessage', msg);
		//重新加载客户端信息
		reConnectOpen();
	} else if (event == "onerror") {
		var msg = {
			errcode: '100500',
			errmsg: 'close websocket'
		};

		console.log("连接异常断开=",event,e,ws);
		ipcRenderer.send('app-socket-onlinemessage', msg)
		setStatusText("已断开连接");
	} else{
		setStatusText("未知状态");
	}
};
